<!DOCTYPE html>
<html lang=zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Chickenrabbit</title>
    <style>
      .container {
        width: 60%;
        margin: 0 auto;
        background-color: aqua;
        min-height: 220px;
      }
      h2 {
        text-align: center;
        padding-top: 10px;
      }
      p {
        width: 90%;
        margin: 0 auto;
        text-align: center;
      }
      input {
        box-sizing: border-box;
        width: 60px;
      }
      p#result {
        margin: 20px auto;
        height: 40px;
        width: 75%;
        padding: 20px;
        border: 1px dotted goldenrod;
        background-color: rgb(221, 220, 220);
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <main class="container">
      <h2>循环解决鸡兔同笼问题</h2>
      <form action="#">
        <p>
          鸡兔同笼,鸡兔一共<input type="text" id="sum" />只。笼子里脚一共<input
            type="text"
            id="foot"
          />只,请问分别有多少只鸡和兔？<input
            type="button"
            value="计算"
            onclick="calculate()"
          />
        </p>
        <p id="result"></p>
      </form>
    </main>
    <script>
      let sum = document.getElementById("sum");
      let foot = document.getElementById("foot");
      let result = document.getElementById("result");
      function calculate() {
        let nowfoot = foot.value - sum.value * 2; //都抬起两条腿后，剩余脚的数量
        let rabbit = nowfoot / 2; //兔子的只数就等于全部都抬起两只脚后，剩余脚的数量除以2
        let chicken = sum.value - rabbit; //鸡的只数
        if (parseInt(nowfoot) % 2 === 0 && chicken >= 0 && rabbit >= 0) {
          result.style.color = "blue";
          result.style.fontWeight = "bold";
          result.innerText = "分别有鸡" + chicken + "只,有兔子" + rabbit + "只";
        } else {
          result.style.color = "red";
          result.style.fontWeight = "bold";
          result.innerText = "无解";
        }
      }
    </script>
  </body>
</html>
